package com.yu.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import org.apache.http.HttpStatus;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * @author Xiujie Yu
 * @Date 2021-01-14
 * @Time 16:19
 * 非法字符过滤器
 */
@Component
public class IllegalCharFilter extends ZuulFilter {

    @Value("${illegal_char}")
    private String illegalChar;

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 6;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        //具体过滤器业务代码
        System.out.println("----进入了非法字符过滤器----");
        //使用zuul中提供的请求上下文对象
        RequestContext currentContext = RequestContext.getCurrentContext();
        //获取response
        HttpServletResponse response = currentContext.getResponse();
        //获取request
        HttpServletRequest request = currentContext.getRequest();
        //获取请求的参数名称集合
        Enumeration<String> names = request.getParameterNames();
        //解析配置的非法字符串
        String[] illegalCharArray = illegalChar.split(",");
        while (names.hasMoreElements()) {
            String s = names.nextElement();
            //根据名字获取值
            String parameterValue = request.getParameter(s);
            //判断parameterValue是否含有非法字符
            for (String s1 : illegalCharArray) {
                if (parameterValue.contains(s1)) {
                    System.out.println("非法字符为："+s1);
                    response.setCharacterEncoding("utf-8");
                    currentContext.setSendZuulResponse(false);
                    try {
                        response.sendError(HttpStatus.SC_FORBIDDEN, "你的请求中含有非法字符，不允许访问");
                        return null;
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return null;
    }
}
